package java8;

import java.io.RandomAccessFile;

/**
 * Auth: bruce-sha
 * Date: 2015/3/11
 * http://www.cnblogs.com/xudong-bupt/archive/2013/04/20/3028980.html
 */
public class RandomAccessFileMain {


    public static void main(String[] args) throws Exception {
//        wrongRead();

//        read();
//        write();
        writeUTF();
    }


    public static void writeUTF() throws Exception {
        RandomAccessFile access = new RandomAccessFile("c:\\a.txt", "rw");    //文件a.txt中只有一个整数1234

        access.writeUTF("12345678");
        access.writeUTF("你好");
        access.writeUTF("朋友");

        access.close();
    }

    public static void write() throws Exception {
        RandomAccessFile access = new RandomAccessFile("c:\\a.txt", "rw");    //文件a.txt中只有一个整数1234

        access.writeInt(1234);

        access.close();
    }

    public static void wrongRead() throws Exception {
        RandomAccessFile access = new RandomAccessFile("c:\\a.txt", "rw");    //文件a.txt中只有一个整数1234
        System.out.println("文件长度为：" + access.length());
//        System.out.println(access.readLine());
//        System.out.println("读出的数据位:" + access.readInt());
        System.out.println(access.readByte());
        System.out.println(access.readByte());
//        System.out.println(access.readChar());
//        System.out.println(access.readChar());

        access.close();
    }

    public static void read() throws Exception {
        RandomAccessFile access = new RandomAccessFile("c:\\a.txt", "rw");    //文件a.txt中只有一个整数1234

        byte context[] = new byte[4];
        access.read(context);   //字节读入，最多读取的字节个数不大于字节数组的长度

        System.out.println(new String(context));

        System.out.println(context[0]);//输出第0个字节
        System.out.println(context[1]);//输出第1个字节
        System.out.println(context[2]);
        System.out.println((char) Byte.toUnsignedInt(context[3]));
        access.close();
    }

}
